import React, { useState, useEffect } from 'react';
import '../index.css';

// 定义类型
interface Result {
  averageCost: number;
  additionalShares: number;
  totalCoset: number;
}

interface FormData {
  initialPrice: string;
  initialShares: string;
  currentPrice: string;
  targetPrice: string;
}

// 自定义 Hook 用于设置页面标题和描述
const usePageMeta = (title: string, description: string) => {
  useEffect(() => {
    document.title = title;
    let metaDescription = document.querySelector('meta[name="description"]') as HTMLMetaElement | null;
    if (!metaDescription) {
      metaDescription = document.createElement('meta');
      metaDescription.name = "description";
      document.head.appendChild(metaDescription);
    }
    metaDescription.content = description;

    return () => {
      document.title = "";
      if (metaDescription) {
        document.head.removeChild(metaDescription);
      }
    };
  }, [title, description]);
};

// 计算盈亏平衡点
const calculateBreakeven = (
  initialPrice: number,
  initialShares: number,
  currentPrice: number,
  targetPrice: number
): Result | null => {
  if (!initialPrice || !initialShares || !currentPrice || !targetPrice || targetPrice <= currentPrice) {
    return null;
  }

  const initialInvestment = initialPrice * initialShares;
  const currentValue = currentPrice * initialShares;
  const loss = initialInvestment - currentValue;

  const additionalShares = Math.round(loss / (targetPrice - currentPrice));
  const totalShares = initialShares + additionalShares;
  const totalCoset = additionalShares * currentPrice;
  const totalInvestment = initialInvestment + totalCoset;
  const averageCost = totalInvestment / totalShares;

  return { additionalShares, averageCost, totalCoset };
};

// 表单组件
const StockForm = ({
  formData,
  handleInputChange,
  handleSubmit,
}: {
  formData: FormData;
  handleInputChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  handleSubmit: (e: React.FormEvent<HTMLFormElement>) => void;
}) => (
  <form onSubmit={handleSubmit}>
    <div className="form-group">
      <label htmlFor="initialPrice" className="form-label">初始买入价格：</label>
      <input
        type="number"
        id="initialPrice"
        name="initialPrice"
        value={formData.initialPrice}
        onChange={handleInputChange}
        step="0.01"
        required
        className="form-input"
      />
    </div>
    <div className="form-group">
      <label htmlFor="initialShares" className="form-label">初始买入数量：</label>
      <input
        type="number"
        id="initialShares"
        name="initialShares"
        value={formData.initialShares}
        onChange={handleInputChange}
        required
        className="form-input"
      />
    </div>
    <div className="form-group">
      <label htmlFor="currentPrice" className="form-label">当前价格：</label>
      <input
        type="number"
        id="currentPrice"
        name="currentPrice"
        value={formData.currentPrice}
        onChange={handleInputChange}
        step="0.01"
        required
        className="form-input"
      />
    </div>
    <div className="form-group">
      <label htmlFor="targetPrice" className="form-label">目标价格：</label>
      <input
        type="number"
        id="targetPrice"
        name="targetPrice"
        value={formData.targetPrice}
        onChange={handleInputChange}
        step="0.01"
        required
        className="form-input"
      />
    </div>
    <button type="submit" className="submit-button">
      计算
    </button>
  </form>
);

// 结果展示组件
const ResultDisplay = ({ result, targetPrice }: { result: Result; targetPrice: string }) => (
  <div className="result-container">
    <p>为了在目标价格 {targetPrice} 元时保本，您需要额外购买 <strong>{result.additionalShares}</strong> 股。共计 {result.totalCoset} 元</p>
    <p>这将使您的平均成本降至 <strong>{result.averageCost.toFixed(2)}</strong> 元。</p>
  </div>
);

// 主组件
const StockBreakevenCalculator = () => {
  const [formData, setFormData] = useState<FormData>({
    initialPrice: '',
    initialShares: '',
    currentPrice: '',
    targetPrice: ''
  });
  const [result, setResult] = useState<Result | null>(null);
  const [isSubmitted, setIsSubmitted] = useState(false);

  usePageMeta(
    "股票回本计算器 - 轻松计算你的投资策略",
    "使用我们的股票回本计算器，轻松计算你需要购买的额外股票数量，以在目标价格时实现盈亏平衡。优化你的投资策略，做出明智的决策。"
  );

  useEffect(() => {
    if (isSubmitted) {
      const { initialPrice, initialShares, currentPrice, targetPrice } = formData;
      const calculationResult = calculateBreakeven(
        parseFloat(initialPrice),
        parseInt(initialShares),
        parseFloat(currentPrice),
        parseFloat(targetPrice)
      );
      setResult(calculationResult);
    }
  }, [formData, isSubmitted]);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prevData => ({
      ...prevData,
      [name]: value
    }));
    setIsSubmitted(false);
  };

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsSubmitted(true);
  };

  return (
    <div className="calculator-container">
      <h1 className="calculator-title">股票回本计算器</h1>
      <StockForm formData={formData} handleInputChange={handleInputChange} handleSubmit={handleSubmit} />
      {isSubmitted && result && <ResultDisplay result={result} targetPrice={formData.targetPrice} />}
      {isSubmitted && !result && (
        <div className="error-message">
          <p>请填写所有字段并点击计算按钮。</p>
        </div>
      )}
    </div>
  );
};

export default StockBreakevenCalculator;